/* eslint-disable max-lines */
import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Drawer, Message, Balloon, Divider, Tab, Checkbox, Dialog } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { ENUMS, column, toSelectDataSource } from './stores/definitions';
import { toJS } from 'mobx';
import NotifyForm from './components/NotifyForm';
import ViewNotify from './components/ViewNotify';

const tableId = uniqueId('tauTable-');

const itemTabs = [
  { key: '0', title: t`未读通知` },
  { key: '1', title: t`已读通知` },
  { key: '2', title: t`已发布通知` },
];

const Notify = () => {
  const [modal, setModal] = useState([]);
  const { notifyStore: store } = useStore();
  const xcxRef = useRef();

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { ...searchArgs } = params.values;
    store.search = {
      ...searchArgs,
    };
  };

  // 添加通知
  const handleAddLine = () => {
    xcxRef.current = {};
    setModal(['add']);
  };

  // 查看通知
  const handleViewNotify = (result) => {
    xcxRef.current = result;
    setModal(['view']);
  };

  // 编辑已读
  const handleEditStatus = async (result) => {
    try {
      await store.update(result?.id);
      Message.success({ content: t`已读成功` });
    } catch (err) {
      Message.error({ content: t`已读失败`, duration: 7000 });
      throw err;
    }
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal([]);
  };

  // 删除通知
  const handleRemove = async (result) => {
    try {
      await store.remove(result?.id);
      Message.success({ content: t`删除成功` });
    } catch (err) {
      Message.error({ content: t`删除失败`, duration: 7000 });
      throw err;
    }
  };

  const handleSendNotify = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.sendNotify({ ...toJS(result) });
        Message.success({ content: t`通知发布成功` });
      } catch (e) {
        Message.error({ content: t`通知发布失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  const handleReadAll = () => {
    Dialog.confirm({
      title: t`确定将所有未读通知标记为已读?`,
      onOk: async () => {
        try {
          await store.myall();
          Message.success({ content: t`全部已读成功` });
        } catch (error) {
          Message.error({ content: t`全部已读错误`, duration: 7000 });
          throw error;
        }
      },
    });
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        actions={[].concat(global.isAdmin ? [
          {
            name: 'btn-addNotify',
            title: t`发布通知`,
            type: 'primary',
            onClick: handleAddLine,
          },
        ] : [])}
        searchItems={[
          {
            name: 'type',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.type),
              placeholder: t`通知类型`,
              style: { width: '200px' },
            },
          },
        ]}
        keywordSearch={{
          placeholder: t`请输入关键字搜索`,
        }}
        className="action-panel"
      />
      <div className="content">
        <Tab
          activeKey={store.notifyStatus}
          onChange={(v) => {
            store.notifyStatus = v;
          }}
          extra={store._notifyStatus === '0' && <Button onClick={(v) => handleReadAll(v)}>{t`全部已读`}</Button>}
        >
          {itemTabs.map((item) => (
            <Tab.Item title={item.title} key={item.key} />
          ))}
        </Tab>
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          onFetch={(pg) => {
            store.pg = pg;
          }}
          loading={store.loading}
          dataSource={toJS(store.notify)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('id', {
              width: 200,
              cell: (v, __, r) => (
                <Button type="primary" text onClick={() => handleViewNotify(r)}>
                  {v}
                </Button>
              ),
            }),
          ].concat(store._notifyStatus === '2' ? [
            column('recipient', { width: 100 }),
          ] : []).concat([
            column('subject', {}),
            column('content', {}),
            column('businessKey', { width: 230 }),
            column('type', {}),
            column('status', {}),
            column('sendTypes', { width: 100 }),
            column('crDate', { width: 126 }),
            {
              title: t`操作`,
              dataIndex: 'Number',
              width: 180,
              cell: (_, i, notify) => {
                const { status } = notify;
                return (
                  <div key={i}>
                    <Balloon
                      v2
                      trigger={<Button type="primary" style={{ color: 'red' }} text>{t`删除`}</Button>}
                      triggerType="hover"
                      title="确定删除吗?"
                    >
                      <Button type="primary" warning onClick={() => handleRemove(notify)}>{t`确定`}</Button>
                    </Balloon>
                    {status === 0 && <Divider direction="ver" />}
                    {status === 0 && (
                      <Balloon
                        v2
                        trigger={<Button type="primary" text>{t`已读`}</Button>}
                        triggerType="hover"
                        title="确认已读?"
                      >
                        <Button type="primary" onClick={() => handleEditStatus(notify)}>{t`确定`}</Button>
                      </Balloon>
                    )}
                  </div>
                );
              },
            },
          ])}
        />
      </div>
      <Drawer
        visible={modal[0] === 'view'}
        title={t`查看通知`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="600px"
      >
        <ViewNotify notify={xcxRef.current} modal={modal} onCancel={handleCancel} onSubmit={() => { }} />
      </Drawer>
      <Drawer
        visible={modal[0] === 'add'}
        title={t`发送通知`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="600px"
      >
        <NotifyForm userInfo={xcxRef.current} modal={modal} onCancel={handleCancel} onSubmit={handleSendNotify} />
      </Drawer>
    </TauPage>
  );
};

export default observer(Notify);
